package com.example.msg;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationManagerCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.collection.ArrayMap;

import android.os.StrictMode;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.JavascriptInterface;

import com.example.msg.utils.HttpUtils;
import com.just.agentweb.WebChromeClient;
import com.just.agentweb.WebViewClient;

import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.widget.LinearLayout;

import com.just.agentweb.AgentWeb;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.Set;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = "HELLO-MainActivity:";
    public static Context context;
    private static final int REQUEST_CODE = 9527;
    private LinearLayout ll_root=null;
    private SharedPreferences sharedPreferences;
    private AgentWeb agentWeb=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(!isNLServiceEnabled()){
            startActivityForResult(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS"), REQUEST_CODE);
        }
        sharedPreferences = getSharedPreferences("test", MODE_PRIVATE);
        context=getApplicationContext();
        ll_root = findViewById(R.id.web);
        String url="file:///android_asset/index.html";
        //url=sharedPreferences.getString("url",url);
        //Log.i(TAG, "onCreate: "+url);
        //url="http://192.168.3.70/index.html";
        //url="file:///android_asset/index.html";
        //url="https://gitee.com/telrobgit/android-msg/raw/master/app/src/main/assets/index.html";

        StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        agentWeb = AgentWeb.with(this)//传入Activity
                .setAgentWebParent(ll_root, new LinearLayout.LayoutParams(-1, -1))
                .closeIndicator() //关闭进度条动画
                //传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams
                //.useDefaultIndicator(-1,3)//使用默认进度条
                .setWebChromeClient(webClient)
                .setWebViewClient(webViewClient)
                .createAgentWeb()
                .ready()//重试
                .go(url);//https,Android9.0要是使用http需要配置
        agentWeb.getWebCreator().getWebView().getSettings().setBlockNetworkImage(true);
        agentWeb.getWebCreator().getWebView().getSettings().setDomStorageEnabled(true);
        agentWeb.getWebCreator().getWebView().getSettings().setJavaScriptEnabled(true);
        agentWeb.getWebCreator().getWebView().setLongClickable(true);
        agentWeb.getWebCreator().getWebView().setOnLongClickListener(new View.OnLongClickListener(){
            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });
        agentWeb.getJsInterfaceHolder().addJavaObject("android", new JsInvorkCall(sharedPreferences,agentWeb));

    }


    //是否开启服务监听功能
    public boolean isNLServiceEnabled() {
        Set<String> packageNames = NotificationManagerCompat.getEnabledListenerPackages(this);
        if (packageNames.contains(getPackageName())) {
            return true;
        }
        return false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i(TAG, "onPause");
        if(agentWeb!=null ){
            agentWeb.getWebLifeCycle().onPause();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "onResume");
        if(agentWeb!=null ){
            agentWeb.getWebLifeCycle().onResume();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy");
        if(agentWeb!=null ){
            agentWeb.getWebLifeCycle().onDestroy();
        }
    }

    private WebViewClient webViewClient=new WebViewClient(){
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            String url=request.getUrl().toString();
            Log.i(TAG, "shouldInterceptRequest: "+url);
            WebResourceResponse webResourceResponse =null;
            if(url.startsWith("https://gitee.com/telrobgit/")){
                InputStream input = HttpUtils.getStream(url);
                String mimeType="text/html";
                if(url.endsWith("html")){
                    mimeType="text/html";
                }else if(url.endsWith("js")){
                    mimeType="application/javascript";
                }
                webResourceResponse = new WebResourceResponse(mimeType, "utf-8", input);
            }else{
                webResourceResponse= super.shouldInterceptRequest(view,request);
            }


            return webResourceResponse;
        }
    };

    private WebChromeClient webClient=new WebChromeClient(){
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            String msg = consoleMessage.message();
            Log.i(TAG, "log:" + msg);
            return super.onConsoleMessage(consoleMessage);
        }
    };

    @Override
    public void onBackPressed() {
        if(agentWeb!=null&&agentWeb.getIEventHandler().back()){
            Log.i(TAG, "go back");
        }else{
            finish();
        }
    }
}
